<template>
    <div>
        <!-- <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 页面已完成 </el-breadcrumb-item>
            </el-breadcrumb>
        </div> -->
        <div class="container">
            <div class="handle-box">
                <el-input
                    v-model="query.username"
                    placeholder="用户名"
                    class="handle-input mr10"
                    clearable
                    @keyup.native.enter="handleSearch()"
                ></el-input>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button type="primary" @click="handleAdd">新增</el-button>
                <!-- <el-button type="danger"
                   class="handle-del"
                   @click="delAllSelection">删除</el-button> -->
            </div>
            <el-table
                :data="tableData"
                border
                class="table"
                ref="multipleTable"
                header-cell-class-name="table-header"
                @selection-change="handleSelectionChange"
                :default-sort="{ prop: 'createTime', order: 'descending' }"
                @sort-change="sortChange"
            >
                <el-table-column type="selection" width="55" align="center"></el-table-column>

                <el-table-column prop="username" label="用户名" align="center" sortable></el-table-column>
                <el-table-column prop="deptName" label="所属部门" align="center"></el-table-column>
                <el-table-column prop="email" label="邮箱" align="center"></el-table-column>
                <el-table-column prop="phone" label="手机号" align="center" sortable></el-table-column>
                <!-- <el-table-column label="状态"
                         align="center"
                         sortable>
          <template slot-scope="scope">
            <el-tag>{{ scope.row.status === 1 ? "正常" : "异常" }}</el-tag>
          </template>
        </el-table-column> -->
                <el-table-column width="auto" label="状态" align="center">
                    <template slot-scope="scope">
                        <img
                            v-if="scope.row.status == 1"
                            style="width: 20px;height: 20px;"
                            src="@/assets/images/歌曲管理/u464.png"
                            alt=""
                        />
                        <img
                            v-else-if="scope.row.status == 0"
                            style="width: 20px;height: 20px;"
                            src="@/assets/images/歌曲管理/u468.png"
                            alt=""
                        />
                    </template>
                </el-table-column>
                <el-table-column label="锁定状态" align="center" sortable>
                    <template slot-scope="scope">
                        <el-tag>{{ scope.row.lockStatus === 1 ? '锁定' : '未锁定' }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" sortable></el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <!-- <el-button type="text"
                       class="red"
                       @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination">
                <el-pagination
                    background
                    layout="total,sizes, prev, pager, next, jumper"
                    :page-sizes="[5, 10, 20, 30, 60]"
                    @size-change="handleSizeChange"
                    :current-page="query.pageIndex"
                    :page-size="query.pageSize"
                    :total="pageTotal"
                    @current-change="handlePageChange"
                ></el-pagination>
            </div>
        </div>

        <!-- 新增&&编辑弹出框 -->
        <el-dialog :title="title" :close-on-click-modal="false" :visible.sync="editVisible" width="50%">
            <el-form ref="form" :model="form" label-width="auto" :rules="rules">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" clearable maxlength="10" minlength="3" placeholder="限制长度为3-10个字符"></el-input>
                </el-form-item>
                <el-form-item label="所属部门" class="is-required" :class="{ 'is-error': depttip }">
                    <div class="block">
                        <el-cascader
                            v-model="deptvalue"
                            @change="handleChange"
                            :options="deptList"
                            :props="{ checkStrictly: false }"
                            ref="cascader"
                            clearable
                        ></el-cascader>
                        <div class="el-form-item__error" v-if="depttip">请选择部门</div>
                    </div>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" clearable v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="confirmPassword">
                    <el-input type="password" clearable v-model="form.confirmPassword"></el-input>
                </el-form-item>
                <el-form-item label="真实姓名">
                    <el-input clearable v-model="form.realName"></el-input>
                </el-form-item>
                <!-- <el-form-item label="性别">
          <el-radio-group v-model="form.gender"
                          size="medium">
            <el-radio :label="0">男</el-radio>
            <el-radio :label="1">女</el-radio>
          </el-radio-group>
        </el-form-item> -->

                <el-form-item label="邮箱">
                    <el-input clearable v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input clearable v-model="form.phone"></el-input>
                </el-form-item>
                <el-form-item label="角色配置" class="is-required" :class="{ 'is-error': roletip }">
                    <div class="block">
                        <el-cascader
                            :options="roleList"
                            v-model="rolevalue"
                            @change="handleMultipleChange"
                            :props="{ multiple: true, checkStrictly: true }"
                            clearable
                        ></el-cascader>
                        <div class="el-form-item__error" v-if="roletip">请选择角色配置</div>
                    </div>
                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="form.status" size="medium">
                        <el-radio :label="1">正常</el-radio>
                        <el-radio :label="0">停用</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="锁定状态">
                    <el-radio-group v-model="form.lockStatus" size="medium">
                        <el-radio :label="0">未锁定</el-radio>
                        <el-radio :label="1">锁定</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import md5 from 'js-md5';
export default {
    name: 'UserManage',

    data() {
        var validateConfirmPassword = (rule, value, callback) => {
            if (value === '') {
                callback(new Error('请再次输入密码'));
            } else if (value !== this.form.password) {
                callback(new Error('两次输入密码不一致!'));
            } else {
                callback();
            }
        };
        return {
            roletip: false,
            depttip: false,
            roleList: [],
            rolevalue: [],
            deptvalue: [],
            title: '',
            increaseFlag: false,
            editFlag: false,
            deptList: [
                {
                    value: '',
                    label: '',
                    children: [
                        {
                            value: '',
                            label: ''
                        }
                    ]
                }
            ],
            query: {
                order: '',
                orderField: '',
                pageIndex: 1,
                pageSize: 10,
                username: '',
                status: 1
            },

            tableData: [
                {
                    adminFlag: '',
                    createBy: '',
                    createTime: '',
                    id: '',
                    lockStatus: 0,
                    status: 1,
                    superFlag: '',
                    supportRoles: [],
                    updateBy: '',
                    updateTime: '',
                    realName: '',
                    gender: '',
                    email: '',
                    phone: '',
                    username: '',
                    deptName: '',
                    deptId: ''
                }
            ],
            multipleSelection: [],
            delList: [],
            editVisible: false,
            pageTotal: 0,
            form: {
                username: '',
                password: '',
                confirmPassword: '',
                realName: '',
                gender: '',
                email: '',
                phone: '',
                status: 1,
                lockStatus: 0,
                deptName: '',
                deptId: '',
                userId: '',
                supportRoles: []
            }, // 无角色配置和所属部门
            rules: {
                username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
                password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
                confirmPassword: [
                    {
                        required: true,
                        validator: validateConfirmPassword,
                        trigger: 'blur'
                    }
                ]
            },
            idx: -1,
            ids: [],
            pwd: '',
            pwdvalue: false
        };
    },

    created() {
        console.log(this.tableData);
        // 真实数据
        this.getSysUser();
    },
    computed: {},
    methods: {
        // 获取数据
        async getSysUser() {
            try {
                const url = '/user/query';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        name: this.query.username,
                        // status: this.query.status,
                        page: this.query.pageIndex - 1,
                        size: this.query.pageSize
                    }
                });
                console.log('用户管理列表：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.pageTotal = res.data.totalElements || 0;
                var dataList = res.data.content;
                this.tableData = [];
                for (var i = 0; i < dataList.length; i++) {
                    this.tableData.push({
                        adminFlag: dataList[i].adminFlag,
                        createBy: dataList[i].createBy,
                        createTime: this.$dateFormat(dataList[i].createTime),
                        id: dataList[i].id,
                        lockStatus: dataList[i].lockStatus,
                        status: dataList[i].status,
                        superFlag: dataList[i].superFlag,
                        supportRoles: dataList[i].supportRoles,
                        updateBy: dataList[i].updateBy,
                        updateTime: dataList[i].updateTime,
                        username: dataList[i].username,
                        deptName: dataList[i].dept ? dataList[i].dept.name : '',
                        email: dataList[i].email,
                        phone: dataList[i].phone,
                        deptId: dataList[i].deptId
                    });
                }
                console.log(this.tableData);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 单选所属部门
        handleChange(value) {
            console.log(value);
            this.form.deptName = value[value.length - 1];
            console.log(this.form.deptName);
        },
        // 多选角色
        handleMultipleChange(value) {
            console.log(value);
            this.rolevalue = value;
            if (this.rolevalue.length > 0) {
                this.roletip = false;
            } else {
                this.roletip = true;
            }
        },
        // 新增
        handleAdd() {
            this.editVisible = true;
            this.editFlag = false;
            this.title = '新增';
            this.form = {
                username: '',
                userId: '',
                password: '',
                phone: '',
                email: '',
                deptId: '',
                roles: [],
                supportRoles: [],
                lockStatus: 0,
                status: 1
            };
            // 初始化角色配置
            this.initRoleList();
            // 初始化所属部门
            this.initDeptList();

            // 标记
            this.increaseFlag = true;
        },
        circle(deptName, deptList) {
            console.log(deptName, deptList);
            for (var i = 0; i < deptList.length; i++) {
                if (deptList[i].name == deptName) {
                    this.deptId = deptList[i].id;
                    return deptList[i].id; // 返回值返回到了this.circle()中去了
                } else if (deptList[i].children && deptList[i].children.length) {
                    console.log(deptName, deptList[i].children);
                    this.circle(deptName, deptList[i].children);
                }
            }
        },
        // 递归思想: 根据deptName查找id
        getDeptId(deptName, deptList) {
            console.log(deptName, deptList);
            this.circle(deptName, deptList);
            return this.deptId;
        },

        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            // console.log(this.multipleSelection);
        },
        // delAllSelection () {
        //   var ids = this.multipleSelection.map((item) => {
        //     return item.id;
        //   });
        //   util.delete.call(this, "/sys/user", "", ids, this.getSysUser);
        // },
        // 根据选择的角色名字 获得id
        getRoleIdList(roleList, rolevalue) {
            console.log(roleList, rolevalue);
            var array = [];
            for (var item of roleList) {
                for (var val of rolevalue) {
                    if (val == item.description) {
                        array.push(item.id);
                    }
                }
            }
            return array;
        },
        async saveAdd() {
            console.log(this.form);
            // 得到成功提示
            try {
                const url = '/user/post';
                let val = {
                    username: this.form.username,
                    userId: this.form.userId,
                    password: md5(this.form.username + this.form.password),
                    phone: this.form.phone,
                    email: this.form.email,
                    deptId: this.getDeptId(this.form.deptName, this.deptList),
                    roles: this.getRoleIdList(this.roleList, this.rolevalue),
                    lockStatus: this.form.lockStatus,
                    status: this.form.status
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('新增用户数据：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.editVisible = false;
                this.$message.success('ok');
                this.increaseFlag = false;
                // 刷新
                this.getSysUser();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 根据选择的
        saveEdit() {
            this.$refs.form.validate(valid => {
                if (valid) {
                    this.roletip = this.rolevalue.length > 0 ? false : true;
                    this.depttip = this.deptvalue != '' ? false : true;
                    if (this.rolevalue.length > 0 && this.deptvalue != '') {
                        // 新增确定进入
                        if (this.increaseFlag) {
                            console.log('新增');
                            this.saveAdd();
                        }

                        // 编辑确定进入
                        if (this.editFlag) {
                            this.pwdvalue = this.form.password == this.pwd ? true : false;
                            this.$message.success('ok');
                            this.$set(this.tableData, this.idx, this.form);
                            this.saveEditData();
                        }
                    }
                }
            });
        },
        async saveEditData() {
            // 得到成功提示
            try {
                console.log(this.getRoleIdList(this.roleList, this.rolevalue));
                console.log(this.getDeptId(this.form.deptName, this.deptList));
                console.log(this.form);
                const url = '/user/update';
                let val = {
                    username: this.form.username,
                    userId: this.form.userId,
                    password: this.pwdvalue ? '' : md5(this.form.username + this.form.password),
                    phone: this.form.phone,
                    email: this.form.email,
                    deptId: this.getDeptId(this.form.deptName, this.deptList),
                    roles: this.getRoleIdList(this.roleList, this.rolevalue),
                    lockStatus: this.form.lockStatus,
                    status: this.form.status
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('编辑用户：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.editFlag = false;
                this.editVisible = false;

                // this.$set(this.query, "status", res.data.status);
                this.getSysUser();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 编辑操作
        handleEdit(index, row) {
            console.log(index, row);
            this.title = '编辑';
            this.idx = index;
            // this.form=row
            this.form.deptId = row.deptId;
            this.editVisible = true;
            this.editFlag = true;
            this.increaseFlag = false;
            // // 初始化所属部门
            this.initDeptList();
            // // 初始化角色配置
            this.initRoleList();
            this.getSingleData(row.id);
        },
        async getSingleData(id) {
            // 获取单个用户信息
            try {
                const url = '/user/get';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        userId: id
                    }
                });
                console.log('当前用户数据：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.form.userId = id;
                for (var key in res.data) {
                    if (key == 'createTime') {
                        this.form[key] = this.$dateFormat(res.data[key]);
                    } else if (key == 'password') {
                        this.form[key] = res.data[key].slice(0, 6);
                        this.form.confirmPassword = res.data[key].slice(0, 6);
                        this.pwd = res.data[key].slice(0, 6);
                    } else if (key == 'dept') {
                        this.form.deptName = res.data[key].name;
                    } else {
                        this.form[key] = res.data[key];
                    }
                }
                console.log(this.form);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getSysUser();
        },
        handleSizeChange(val) {
            this.$set(this.query, 'pageSize', val);
            this.getSysUser();
        },
        // // 删除操作
        // handleDelete (index, row) {
        //   this.ids[0] = row.id;
        //   util.delete.call(this, "/sys/user", index, this.ids, this.getSysUser);
        // },
        // 初始化所属部门
        async initDeptList() {
            try {
                const url = '/dept/query';
                const { data: res } = await this.$http[4].get(url);
                console.log('部门列表：', res);
                if (res.code !== '0000') {
                    return;
                }
                var data = res.data.content;
                // 调用递归
                this.addLabelAttribute('dept', data);
                this.deptList = data;
                console.log(this.deptList);
                console.log(this.form);
                let dId = [];
                this.deptList.map(item => {
                    if (item.id == this.form.deptId) {
                        // this.deptvalue = item.name;
                        // console.log(this.deptvalue)
                        dId.push(item.name);
                    }
                });
                this.deptvalue = dId.length > 0 ? dId[0] : '';
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 初始化角色配置
        async initRoleList() {
            try {
                const url = '/role/query';
                const { data: res } = await this.$http[4].get(
                    url
                    // , {
                    //   params: {
                    //     name: '',
                    //     status: this.query.status,
                    //   }
                    // }
                );
                console.log('角色列表：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.addLabelAttribute('role', res.data.content);
                this.roleList = res.data.content;
                this.rolevalue = [];
                // console.log(this.form)
                if (this.form.supportRoles.length > 0) {
                    console.log('aaaa:', this.roleList, this.form.supportRoles);
                    for (var val of this.form.supportRoles) {
                        this.roleList.map(item => {
                            if (val.id == item.id) {
                                this.rolevalue.push(item.description);
                            }
                        });
                    }
                }
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //   message: err.message,
                //   duration: 1500
                // });
            }
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            // this.$set(this.query, "status", '');
            this.tableData = [];
            this.getSysUser();
        },

        // 递归思想: 添加label属性
        addLabelAttribute(type, arr) {
            for (var i = 0; i < arr.length; i++) {
                if ('children' in arr[i] && arr[i].children.length !== 0) {
                    arr[i].label = type == 'role' ? arr[i].description : arr[i].name;
                    arr[i].value = type == 'role' ? arr[i].description : arr[i].name;
                    this.addLabelAttribute(type, arr[i].children);
                } else if ('children' in arr[i] && arr[i].children.length === 0) {
                    arr[i].label = type == 'role' ? arr[i].description : arr[i].name;
                    arr[i].value = type == 'role' ? arr[i].description : arr[i].name;
                    delete arr[i].children;
                } else if (!('children' in arr[i])) {
                    arr[i].label = type == 'role' ? arr[i].description : arr[i].name;
                    arr[i].value = type == 'role' ? arr[i].description : arr[i].name;
                }
            }
        },
        // 表头排序
        sortChange({ column, prop, order }) {
            prop = prop === 'createTime' ? 'create_date' : prop;
            this.$set(this.query, 'orderField', prop);
            if (order === 'ascending') {
                this.$set(this.query, 'order', order.substr(0, 3));
                console.log('ascending');
                this.getSysUser();
            } else if (order === 'descending') {
                this.$set(this.query, 'order', order.substr(0, 4));
                console.log('descending');
                this.getSysUser();
            }
        }
    },
    watch: {
        deptvalue() {
            if (this.$refs.cascader) {
                this.$refs.cascader.dropDownVisible = false;
            }
            // this.depttip = this.deptvalue != '' ? false : true
        }
    }
};
</script>

<style lang="scss">
.el-cascader-panel .el-checkbox {
    width: 90%;
    height: 100%;
    z-index: 10;
    position: absolute;
    // top: 10px;
    right: 10px;
}

// .el-cascader-panel .el-checkbox__input {
//     visibility: hidden;
// }
/* 这个样式针对IE有用，不考虑IE的可以不用管*/
.el-cascader-panel .el-cascader-node__postfix {
    top: 10px;
}
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    width: 120px;
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
